import 'package:flutter/material.dart';
import 'models/contact.dart';
import 'services/contact_service.dart';
import 'contact_form.dart';
import 'utils/custom_route.dart';

class ContactList extends StatefulWidget {
  const ContactList({super.key});

  @override
  State<ContactList> createState() => _ContactListState();
}

class _ContactListState extends State<ContactList> {
  final ContactService _contactService = ContactService();
  List<Contact> contacts = [];
  bool _isSearching = false;
  final TextEditingController _searchController = TextEditingController();
  late List<Contact> _filteredContacts;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadContacts();
    _searchController.addListener(_filterContacts);
  }

  // 加载联系人数据
  Future<void> _loadContacts() async {
    try {
      final loadedContacts = await _contactService.getContacts();
      setState(() {
        contacts = loadedContacts;
        _filteredContacts = contacts;
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载联系人失败: ${e.toString()}')),
      );
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 保存联系人数据
  Future<void> _saveContacts() async {
    try {
      await _contactService.saveContacts(contacts);
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('保存联系人失败: ${e.toString()}')),
      );
    }
  }

  // 添加联系人
  Future<void> _addContact() async {
    final result = await Navigator.push<dynamic>(
      context,
      SlideRightRoute(page: const ContactForm()),
    );
    
    if (result != null && result is Contact) {
      setState(() {
        contacts.add(result);
        _filteredContacts = contacts;
      });
      await _saveContacts();
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('联系人添加成功')),
      );
    }
  }

  // 编辑联系人
  Future<void> _editContact(int index, Contact contact) async {
    final result = await Navigator.push<dynamic>(
      context,
      SlideRightRoute(page: ContactForm(contact: contact)),
    );
    
    if (result != null) {
      setState(() {
        if (result == 'delete') {
          contacts.removeAt(index);
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('联系人已删除')),
          );
        } else if (result is Contact) {
          contacts[index] = result;
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('联系人已更新')),
          );
        }
        _filteredContacts = contacts;
      });
      await _saveContacts();
    }
  }

  // 过滤联系人
  void _filterContacts() {
    final query = _searchController.text.toLowerCase();
    setState(() {
      if (query.isEmpty) {
        _filteredContacts = contacts;
      } else {
        _filteredContacts = contacts.where((contact) {
          return contact.name.toLowerCase().contains(query) ||
              contact.phone.contains(query);
        }).toList();
      }
    });
  }

  // 构建搜索栏
  Widget _buildSearchField() {
    return TextField(
      controller: _searchController,
      autofocus: true,
      decoration: InputDecoration(
        hintText: '搜索联系人...',
        border: InputBorder.none,
        hintStyle: TextStyle(color: Colors.grey[400]),
        prefixIcon: const Icon(Icons.search),
        suffixIcon: IconButton(
          icon: const Icon(Icons.clear),
          onPressed: () {
            _searchController.clear();
          },
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: _isSearching ? _buildSearchField() : const Text('联系人列表'),
        actions: [
          IconButton(
            icon: Icon(_isSearching ? Icons.close : Icons.search),
            onPressed: () {
              setState(() {
                _isSearching = !_isSearching;
                if (!_isSearching) {
                  _searchController.clear();
                }
              });
            },
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : Column(
              children: [
                if (_isSearching)
                  Container(
                    padding: const EdgeInsets.all(8),
                    color: Colors.grey[200],
                    child: Row(
                      children: [
                        Text(
                          '找到 ${_filteredContacts.length} 个联系人',
                          style: const TextStyle(color: Colors.grey),
                        ),
                      ],
                    ),
                  ),
                Expanded(
                  child: _filteredContacts.isEmpty
                      ? Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                _isSearching ? Icons.search_off : Icons.person_off,
                                size: 48,
                                color: Colors.grey[400],
                              ),
                              const SizedBox(height: 16),
                              Text(
                                _isSearching ? '未找到联系人' : '暂无联系人',
                                style: TextStyle(
                                  color: Colors.grey[600],
                                  fontSize: 16,
                                ),
                              ),
                            ],
                          ),
                        )
                      : ListView.builder(
                          itemCount: _filteredContacts.length,
                          itemBuilder: (context, index) {
                            final contact = _filteredContacts[index];
                            return Card(
                              margin: const EdgeInsets.all(8),
                              child: ListTile(
                                leading: CircleAvatar(
                                  backgroundImage: NetworkImage(contact.avatar),
                                  child: Text(
                                    contact.name[0],
                                    style: const TextStyle(
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                                title: Text(
                                  contact.name,
                                  style: const TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16,
                                  ),
                                ),
                                subtitle: Text(contact.phone),
                                trailing: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    IconButton(
                                      icon: const Icon(Icons.message),
                                      onPressed: () {
                                        ScaffoldMessenger.of(context).showSnackBar(
                                          SnackBar(
                                            content: Text('发送消息给 ${contact.name}'),
                                            duration: const Duration(seconds: 1),
                                          ),
                                        );
                                      },
                                    ),
                                    IconButton(
                                      icon: const Icon(Icons.phone),
                                      onPressed: () {
                                        ScaffoldMessenger.of(context).showSnackBar(
                                          SnackBar(
                                            content: Text('拨打电话给 ${contact.name}'),
                                            duration: const Duration(seconds: 1),
                                          ),
                                        );
                                      },
                                    ),
                                  ],
                                ),
                                onTap: () => _editContact(index, contact),
                              ),
                            );
                          },
                        ),
                ),
              ],
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addContact,
        child: const Icon(Icons.add),
      ),
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }
}

